package com.example.yskjproject.ui.fragment;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewbinding.ViewBinding;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.example.yskjproject.R;
import com.example.yskjproject.base.BaseFragment;
import com.example.yskjproject.databinding.ContentFragmentBinding;
import com.example.yskjproject.http.APIService;
import com.example.yskjproject.http.Urls;
import com.example.yskjproject.model.LeftMenuModel;
import com.example.yskjproject.model.LeftModel;
import com.example.yskjproject.model.LzyResponse;
import com.example.yskjproject.utils.Log;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.common.collect.Lists;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 传递过来数据 有筛选条件的fragment
 */
public class ContentFragment extends BaseFragment<ContentFragmentBinding> {

    private ContentFragmentBinding binding;

    private TabLayoutMediator mediator;

    private List<LeftMenuModel> level2Date = Lists.newArrayList();

    private int level1Id;

    public ContentFragment(){
    }

    public ContentFragment(int level1Id){
        this.level1Id = level1Id;
    }

    @Override
    protected ContentFragmentBinding onCreateViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup parent) {
        binding = ContentFragmentBinding.inflate(inflater, parent, false);
        return binding;
    }
    @Override
    protected void onData() {
        new Thread(this::getLevel2).start();
    }

    /**
     * 获取二级菜单
     */
    private void getLevel2() {
        Type type = new TypeToken<LzyResponse<LeftModel>>() {
        }.getType();
        APIService.<LzyResponse<LeftModel>>getData(type, Urls.LIST_LEVEL + "?level=2").subscribeOn(Schedulers.io()).map(response -> response.data).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<LeftModel>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.e("onSubscribe ： " + d);
            }

            @SuppressLint({"NotifyDataSetChanged", "UseRequireInsteadOfGet"})
            @Override
            public void onNext(LeftModel leftLevel2Model) {
                if (leftLevel2Model == null || leftLevel2Model.getTag_list() == null) {
                    return;
                }
                if (leftLevel2Model.getTag_list().isEmpty()) {
                    return;
                }
                level2Date.clear();
                level2Date.addAll(leftLevel2Model.getTag_list());


                binding.viewPager.setOffscreenPageLimit(ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT);
                if (getActivity() == null) {
                    return;
                }
                binding.viewPager.setAdapter(new FragmentStateAdapter(getActivity().getSupportFragmentManager(), getLifecycle()) {
                    @NonNull
                    @Override
                    public Fragment createFragment(int position) {
                        return UniversalDisplayFragment.newInstance(level1Id,level2Date.get(position).getId());
                    }

                    @Override
                    public int getItemCount() {
                        return level2Date.size();
                    }
                });

                //viewPager 页面切换监听监听
                mediator = new TabLayoutMediator(binding.tabTopLayout, binding.viewPager, (tab, i) -> {
                    tab.setText(level2Date.get(i).getName());
                });
                mediator.attach();
                binding.tabTopLayout.setSelectedTabIndicator(null);//使用这个方法
                for (int i = 0; i < binding.tabTopLayout.getTabCount(); i++) {
                    TabLayout.Tab tab = binding.tabTopLayout.getTabAt(i);
                    if (tab != null) {
                        // 设置TabItem的背景
                        TextView tabTextView = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.tab_layout, binding.tabTopLayout, false);
                        tabTextView.setText(level2Date.get(i).getName()); // 设置Tab文本
                        tab.setCustomView(tabTextView);
//                        View tabView = tab.getCustomView();
//                        tabView.setBackgroundResource(R.drawable.tab_itme);
//                        tabTextView.setTextColor(ContextCompat.getColorStateList(this, R.color.tab_text_color));
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();            //请求失败
                Log.e("onError ： " + "获取失败");
            }

            @Override
            public void onComplete() {

            }
        }); //
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }


    @Override
    public void onDestroy() {
        if (mediator != null) {
            mediator.detach();
        }
        super.onDestroy();
    }
}
